import isomorphicFetch from 'isomorphic-fetch'
import {SWITCH_LOADING, SWITCH_FETCHING, SWITCH_MASK, SET_LOGIN_TOKEN, ADD_TO_CART, SHOW_MESSAGE, HIDE_MESSAGE, HIDE_FOOTER, GET_CART_COUNT, SHOW_EMPTYSTATION, HIDE_EMPTYSTATION} from '../../config/ActionType'
import {API_LOGIN_AUTH, fetch, API_GET_LOGIN_TOKEN, API_ADD_TO_CART, API_GET_WECHAT_SHARE, API_GET_WECHAT_CONFIG, API_GET_CART_COUNT} from '../../config/Api'
import {hashHistory} from 'react-router'

export const pageLoading = (status = false) => ({
  type: SWITCH_LOADING,
  payload: {isLoading: status}
})

export const setLoginToken = (token, binded) => ({
  type: SET_LOGIN_TOKEN,
  payload: {token, binded}
})

export const switchFetching = status => ({
  type: SWITCH_FETCHING,
  payload: {status}
})

export const switchMask = status => ({
  type: SWITCH_MASK,
  payload: {status}
})

export const showMessage = text => ({
  type: SHOW_MESSAGE,
  payload: {text}
})

export const showEmptyStation = text => ({
  type: SHOW_EMPTYSTATION,
  payload: {text}
})

export const hideFooter = status => ({
  type: HIDE_FOOTER,
  payload: {status}
})

export const hideMessage = () => ({type: HIDE_MESSAGE})

export const hideEmptyStation = () => ({type: HIDE_EMPTYSTATION})

export function getParams(name) {
  let reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i')
  let r = window.location.search.substr(1).match(reg)

  if (r != null) {
    return unescape(r[2])
  }

  return null
}

export function loginAuth() {
  let code = getParams('code'),
    state = getParams('state'),
    urlList = state.split('fen')

  urlList.shift()
  let url = urlList.join('/')

  return (dispatch, getState) => isomorphicFetch(`${API_LOGIN_AUTH.url}?code=${code}&state=${state}`, Object.assign({}, API_LOGIN_AUTH.config))
    .then(res => res.json())
    .then(json => {
      if (json.success) {
        sessionStorage.setItem('token', json.data.loginToken || null)
        dispatch(setLoginToken(json.data.loginToken || null, json.data.telephoneBind))
        let stateUrl = state.split('fen')

        if (stateUrl.map(item => item || false).indexOf(false) == -1 && stateUrl.length > 1) {
          hashHistory.replace(`/${url}`)
        } else {
          hashHistory.replace('/home')
        }
      } else {
        dispatch(showMessage(json.message))
      }
    })
}

export function fetchWechatConfig(params) {
  let headers = new Headers(),
    body = new FormData()

  headers.append('login-token', sessionStorage.getItem('token'))

  for (let i in params) {
    body.append(i, params[i])
  }

  return (dispatch, getState) => isomorphicFetch(API_GET_WECHAT_CONFIG.url, Object.assign({}, API_GET_WECHAT_CONFIG.config, {headers, body}))
    .then(res => res.json())
    .then(json => {
      if (json.success) {
        const data = json.data

        wx.config({

					// Debug: true,
          appId: data.appId,
          timestamp: data.timestamp,
          nonceStr: data.nonceStr,
          signature: data.signature,
          jsApiList: ['scanQRCode', 'chooseWXPay', 'onMenuShareAppMessage', 'onMenuShareTimeline']
        })
      } else {
        dispatch(showMessage(json.message))
      }
    })
}
export function fetchWechatShare(wtitle, wdesc, wimg, param) {
  let headers = new Headers(),
    body = new FormData()

  param = param || 'share'
  headers.append('login-token', sessionStorage.getItem('token'))
  body.append('param', param)

  return (dispatch, getState) => isomorphicFetch(API_GET_WECHAT_SHARE.url, Object.assign({}, API_GET_WECHAT_CONFIG.config, {headers, body}))
    .then(res => res.json())
    .then(json => {
      if (json.success) {
        const data = json.data

        wimg = wimg || data.imgUrl
        wtitle = wtitle || data.title
        wdesc = wdesc || data.desc
        wx.onMenuShareTimeline({
          title: wtitle,
          link: data.link,
          imgUrl: wimg,
          success() {
            dispatch(showMessage('分享成功'))
          }
        })

        wx.onMenuShareAppMessage({
          title: wtitle,
          desc: wdesc,
          link: data.link,
          imgUrl: wimg,
          success() {
            dispatch(showMessage('分享成功'))
          }
        })
      } else {
        dispatch(showMessage(json.message))
      }
    })
}

export const addToCart = (status = false) => ({
  type: ADD_TO_CART,
  payload: {status}
})

export function fetchAddToCart(params) {
  return (dispatch, getState) => fetch(API_ADD_TO_CART, params)(dispatch, getState).then(json => {
    if (!params.noMessage && json.success) {
      fetchCartCount()(dispatch, getState)
      dispatch(showMessage('添加成功'))
    } else if (!json.success) {
      dispatch(showMessage(json.message))
    }

    return json
  })
}

export const getCartCount = number => ({
  type: GET_CART_COUNT,
  payload: {number}
})

export function fetchCartCount() {
  let headers = new Headers()

  headers.append('login-token', sessionStorage.getItem('token'))

  return dispatch => isomorphicFetch(API_GET_CART_COUNT.url, Object.assign({}, API_GET_CART_COUNT.config, {headers}))
    .then(res => res.json())
    .then(json => {
      if (json.success) {
        dispatch(getCartCount(json.data))
      }

      return json
    })
}

export const actions = {
  pageLoading,
  setLoginToken,
  fetchAddToCart,
  switchFetching,
  switchMask,
  showMessage,
  hideMessage,
  loginAuth,
  hideFooter,
  fetchWechatConfig,
  fetchWechatShare,
  getCartCount,
  fetchCartCount,
  showEmptyStation,
  hideEmptyStation
}

export const ACTION_HANDLERS = {
  [SWITCH_LOADING]: (state, action) => ({...state, isLoading: action.payload.isLoading}),
  [SET_LOGIN_TOKEN]: (state, action) => ({...state, token: action.payload.token, binded: action.payload.binded}),
  [SWITCH_FETCHING]: (state, action) => ({...state, fetching: action.payload.status}),
  [SWITCH_MASK]: (state, action) => ({...state, isMask: action.payload.status}),
  [SHOW_MESSAGE]: (state, action) => ({...state, ifMessage: true, message: action.payload.text}),
  [HIDE_MESSAGE]: (state, action) => ({...state, ifMessage: false}),
  [HIDE_FOOTER]: (state, action) => ({...state, noFooter: action.payload.status}),
  [GET_CART_COUNT]: (state, action) => ({...state, cartCount: action.payload.number}),
  [SHOW_EMPTYSTATION]: (state, action) => ({...state, ifEmptyStation: true, message: action.payload.text}),
  [HIDE_EMPTYSTATION]: (state, action) => ({...state, ifEmptyStation: false})
}

const initialState = {
  isLoading: false,
  token: sessionStorage.getItem('token') || 0,
  fetching: false,
  isMask: false,
  ifMessage: false,
  ifEmptyStation: false,
  message: undefined,
  noFooter: false,
  binded: false,
  cartCount: undefined
}

export default function(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}
